import React, { useCallback, useState, useRef, useEffect, useMemo } from 'react';
import ProgressiveImage from '../../../components/ProgressiveImage';
import { AIPerson } from '../../../types/index';
import { useTranslation } from '../../../i18n/react-i18next';
import './aiPersonCard.css'; // 导入独立的CSS文件
import { getDynamicFonts } from '@/utils/fontUtils';
// import { useNavigate } from 'react-router-dom';

// 添加防止长按选中的样式
const noSelectStyle: React.CSSProperties = {
    WebkitTouchCallout: 'none', // iOS Safari
    WebkitUserSelect: 'none',   // Safari
    KhtmlUserSelect: 'none',    // Konqueror HTML
    MozUserSelect: 'none',      // Firefox
    msUserSelect: 'none',       // Internet Explorer/Edge
    userSelect: 'none',         // 标准语法
    WebkitTapHighlightColor: 'transparent', // 移除点击高亮
};

interface AiPersonCardProps { 
    content: AIPerson;
    onClick: (id: string | number) => void;
}

// 🚀 性能优化：将设备检测移到组件外部，避免每次渲染都执行
const isMobileDevice = (() => {
    if (typeof navigator === 'undefined') return false;
    return /android|iPad|iPhone|iPod|webOS|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent);
})();

const AiPersonCard: React.FC<AiPersonCardProps> = React.memo(({ content, onClick }) => {
    const { t, i18n } = useTranslation();
    const dynamicFonts = getDynamicFonts(i18n);
    const [isTouched, setIsTouched] = useState(false);
    const [isHoveringMainImage, setIsHoveringMainImage] = useState(false);
    const [isVideoReady, setIsVideoReady] = useState(false);
    const [isVideoPlaying, setIsVideoPlaying] = useState(false);
    const videoRef = useRef<HTMLVideoElement>(null);
    const touchStartTimeRef = useRef<number>(0);
    const [isLongTouch, setIsLongTouch] = useState(false);
    // 🔧 新增：用于管理setTimeout的ref，防止内存泄漏
    const longTouchTimeoutRef = useRef<NodeJS.Timeout | null>(null);
    // const navigate = useNavigate();

    // 🚀 性能优化：使用useMemo缓存视频相关计算
    const videoConfig = useMemo(() => {
        const profileVideos = content.videos || content.character_profile?.videos;
        const hasVideo = Array.isArray(profileVideos) && profileVideos.length > 0;
        const firstVideoSrc = hasVideo && profileVideos ? profileVideos[0] : '';
        return { hasVideo, firstVideoSrc, profileVideos };
    }, [content.videos, content.character_profile?.videos]);

    const { hasVideo, firstVideoSrc } = videoConfig;

    // 🚀 性能优化：使用useMemo缓存图片URL处理结果
    const processedImageUrl = useMemo(() => {
        const processImageUrl = (url: string): string => {
            if (!url) return '';
            // 拼接 OSS 图片处理参数，宽度为 600
            const ossParam = 'x-oss-process=image/resize,w_700';
            // 如果已经有参数，追加，否则加 ?
            if (url.includes('?')) {
                return url + '&' + ossParam;
            } else {
                return url + '?' + ossParam;
            }
        };

        return processImageUrl(content.image);
    }, [content.image]);

    // 🚀 性能优化：使用useMemo缓存是否显示视频的计算
    const shouldShowVideo = useMemo(() => {
        return hasVideo && isVideoReady && (isTouched || isHoveringMainImage);
    }, [hasVideo, isVideoReady, isTouched, isHoveringMainImage]);

    // 🚀 性能优化：使用useCallback缓存事件处理函数
    const handleClick = useCallback(() => {
        if (!isLongTouch) {
            onClick(content.id);
        }
    }, [content.id, onClick, isLongTouch]);

    // 阻止默认的长按菜单
    const handleContextMenu = useCallback((e: React.MouseEvent | React.TouchEvent) => {
        e.preventDefault();
        e.stopPropagation();
        return false;
    }, []);

    const playVideo = useCallback(() => {
        if (hasVideo && videoRef.current) {
            videoRef.current.play().catch(() => {
                setIsVideoPlaying(false);
            });
            setIsVideoPlaying(true);
        }
    }, [hasVideo]);

    const stopVideo = useCallback(() => {
        if (videoRef.current && isVideoPlaying) {
            setIsVideoPlaying(false);
            videoRef.current.pause();
            videoRef.current.currentTime = 0;
        }
    }, [isVideoPlaying]);

    // 监听isTouched状态变化，立即播放或停止视频
    useEffect(() => {
        if (isTouched && hasVideo && isVideoReady) {
            playVideo();
        } else if (!isTouched && isVideoPlaying) {
            stopVideo();
        }
    }, [isTouched, hasVideo, isVideoReady, isVideoPlaying, playVideo, stopVideo]);

    const handleTouchStart = useCallback(() => {
        setIsTouched(true);
        touchStartTimeRef.current = Date.now();
        if (hasVideo && videoRef.current) {
            videoRef.current.play().catch(() => {
                setIsVideoReady(false);
            });
        }
    }, [hasVideo]);

    const handleTouchMove = useCallback(() => {
        // 保持触摸状态
    }, []);

    const handleTouchEnd = useCallback(() => {
        setIsTouched(false);
        stopVideo(); // 确保手指移开时视频暂停并重置
        const touchDuration = Date.now() - touchStartTimeRef.current;

        if (touchDuration < 200) {
            setIsLongTouch(false);
        } else {
            setIsLongTouch(true);
            // 🔧 修复：清理之前的timeout并保存新的timeout引用
            if (longTouchTimeoutRef.current) {
                clearTimeout(longTouchTimeoutRef.current);
            }
            longTouchTimeoutRef.current = setTimeout(() => {
                setIsLongTouch(false);
                longTouchTimeoutRef.current = null;
            }, 100);
        }
    }, [stopVideo]);

    const handleMainImageMouseEnter = useCallback(() => {
        if (!hasVideo) return;
        setIsHoveringMainImage(true);
        if (videoRef.current) {
            videoRef.current.play().catch(() => { });
        }
    }, [hasVideo]);

    const handleMainImageMouseLeave = useCallback(() => {
        if (!hasVideo) return;
        setIsHoveringMainImage(false);
        if (videoRef.current) {
            videoRef.current.pause();
            videoRef.current.currentTime = 0;
        }
    }, [hasVideo]);

    // 处理视频加载和预加载
    useEffect(() => {
        if (hasVideo && videoRef.current) {
            const videoElement = videoRef.current;
            const handleCanPlay = () => {
                setIsVideoReady(true);
                if (isTouched) {
                    playVideo();
                }
            };

            videoElement.addEventListener('canplaythrough', handleCanPlay);
            videoElement.preload = "auto";

            return () => {
                videoElement.removeEventListener('canplaythrough', handleCanPlay);
            };
        }
    }, [hasVideo, isTouched, playVideo]);

    // 🔧 新增：组件卸载时清理所有timeout，防止内存泄漏
    useEffect(() => {
        return () => {
            if (longTouchTimeoutRef.current) {
                clearTimeout(longTouchTimeoutRef.current);
                longTouchTimeoutRef.current = null;
            }
        };
    }, []);

    // 🚀 性能优化：移除不必要的图片处理函数，直接使用缓存的结果

    return (
        <div
            className="relative w-full h-full"
            style={{
                marginBottom: 0, // 移除底部 margin，由父容器的 gap 来控制间距
                maxWidth: '100%' // 确保完全填充父容器
            }}
        >
            {/* 外层容器 */}
            <div
                className={`relative p-[2px] h-full rounded-3xl bg-transparent card-container ${isTouched ? 'active' : ''}`}
                style={{
                    transformStyle: 'preserve-3d',
                    willChange: 'transform',
                    ...noSelectStyle, // 添加防止选中的样式

                }}
                onTouchStart={handleTouchStart}
                onTouchMove={handleTouchMove}
                onTouchEnd={handleTouchEnd}
                onContextMenu={handleContextMenu}
            >
                {/* 渐变边框背景 */}
                <div
                    className="absolute inset-0 rounded-3xl card-border"
                    style={{
                        background: 'linear-gradient(to right, #ec4899, #a855f7)',
                        zIndex: -1,

                    }}
                />

                {/* 卡片内容 */}
                <div
                    className="bg-card-dark h-full rounded-3xl overflow-hidden relative cursor-pointer shadow-md card-content"
                    onClick={handleClick}
                    onMouseEnter={handleMainImageMouseEnter}
                    onMouseLeave={handleMainImageMouseLeave}
                    style={noSelectStyle} // 添加防止选中的样式
                >
                    {/* 大图区域 - Main image area (全宽) - 严格 1080 x 1920 比例 */}
                    <div
                        className="relative w-full h-full min-w-0 overflow-hidden"
                        style={{
                            aspectRatio: '9/16', // 严格保持 9:16 比例
                            ...noSelectStyle
                        }}
                    >
                        {content.isPremium && (
                            <div className="absolute z-20 top-2 left-2 bg-pink-600 text-white text-xs font-bold px-2 py-1 rounded-3xl" style={noSelectStyle}>
                                <i className="fas fa-crown mr-1"></i> {t('common.premium')}
                            </div>
                        )}
                        <div
                            className="overflow-hidden relative w-full h-full"
                            style={{
                                aspectRatio: '9/16', // 确保这一层也保持严格比例
                                ...noSelectStyle
                            }}
                        >
                            {/* 主图层 */}
                            <div
                                className="absolute inset-0 z-10"
                                style={{
                                    ...noSelectStyle,
                                    opacity: shouldShowVideo ? 0 : 1,
                                    transition: 'opacity 0.3s ease-in-out'
                                }}
                            >
                                <ProgressiveImage
                                    src={processedImageUrl}
                                    alt={content.username}
                                    className="w-full h-full"
                                    placeholderColor="#1a1a1a"
                                    priority={true} // 设置为高优先级，立即检查缓存并加载
                                    imgStyle={{
                                        width: '100%',
                                        height: '100%',
                                        aspectRatio: '9/16', // 严格保持 9:16 比例
                                        objectFit: 'contain', // 确保完整显示图片内容
                                        objectPosition: 'center', // 居中显示
                                        display: shouldShowVideo ? 'none' : 'block',
                                        backgroundColor: '#1a1a1a', // 添加深色背景以美化可能的空白区域
                                        ...noSelectStyle
                                    }}
                                />
                            </div>

                            {/* 视频层 */}
                            {hasVideo && (
                                <div className="absolute inset-0 z-5" style={noSelectStyle}>
                                    <video
                                        ref={videoRef}
                                        src={firstVideoSrc}
                                        className={`w-full h-full ${isVideoPlaying ? 'playing' : ''}`}
                                        style={{
                                            width: '100%',
                                            height: '100%',
                                            aspectRatio: '9/16', // 严格保持 9:16 比例
                                            objectFit: 'contain', // 确保完整显示视频内容
                                            objectPosition: 'center', // 居中显示
                                            display: shouldShowVideo ? 'block' : 'none',
                                            backgroundColor: '#1a1a1a', // 添加深色背景以美化可能的空白区域
                                            ...noSelectStyle
                                        }}
                                        muted
                                        playsInline
                                        loop
                                        preload="auto"
                                    />
                                </div>
                            )}
                        </div>
                        {/* 文本区域 - 绝对定位覆盖在图片底部 */}
                        <div
                            className={`absolute left-0 right-0 bottom-0 z-30 bg-gradient-to-t from-black/70 via-black/40 to-transparent ${isMobileDevice ? 'p-2' : 'p-3 lg:p-4'
                                }`}
                            style={{
                                ...noSelectStyle,
                                pointerEvents: 'none', // 避免遮挡点击
                                fontFamily: dynamicFonts.font1,
                            }}
                        >
                            <div className="flex items-center space-x-2 mb-1">
                                {/* <div className="flex-shrink-0">
                                    <ProgressiveImage
                                        src={processImageUrl(content.avatar)}
                                        alt={content.username}
                                        className="w-6 h-6 rounded-full object-cover object-[center_0%]"
                                        width={22}
                                        height={22}
                                        placeholderColor="#3a3a3a"
                                        imgStyle={{ objectPosition: 'center 0%', ...noSelectStyle }}
                                    />
                                </div> */}
                                <div className="min-w-0 flex-1">
                                    <div                                     className={`
    ${isMobileDevice ? 'text-[1.2rem]' : 'text-base lg:text-lg xl:text-[1.6rem]'} 
    truncate 
    text-white 
    mb-[-0.3rem]
    font-medium
  `} style={noSelectStyle}>{content.username}
                                        {(content.age || content.character_profile?.basic_info?.age) && (
                                            <span className={`ml-2 ${isMobileDevice ? 'text-[1.1rem]' : 'text-[1.6rem]'}`} style={{ color: "rgb(200,200,200)" }}>
                                                {content.age || content.character_profile?.basic_info?.age}
                                            </span>
                                        )}
                                    </div>
                                    {/* <div className="text-xs h-7 text-gray-300" style={noSelectStyle}>{content.title}</div> */}
                                </div>
                            </div>
                            {content.description && (
                                <div className={`
                                    ${isMobileDevice ? 'text-[0.9rem]' : 'text-xs lg:text-[0.9rem]'} 
                                    text-gray-300 
                                    line-clamp-2
                                    leading-tight
                                  `}
                                    style={{
                                        ...noSelectStyle,
                                        fontFamily: dynamicFonts.font2
                                    }}>
                                    {content.description}
                                </div>
                            )}
                        </div>
                    </div>
                </div>
            </div>
        </div>
    );
}, (prevProps, nextProps) => {
    // 性能优化：比较关键属性以决定是否重新渲染
    return prevProps.content.id === nextProps.content.id &&
        prevProps.content.username === nextProps.content.username &&
        prevProps.content.description === nextProps.content.description;
});

AiPersonCard.displayName = 'AiPersonCard';

export default AiPersonCard;